// src/hooks/useTableRequest.ts
import { useState, useEffect, useCallback, useRef } from 'react';
import { PaginationProps } from 'antd';
import request from '@/utils/request';
import dayjs from 'dayjs';

interface UseTableRequestOptions<T> {
  url: string;
  orderBy?:string;
  defaultCurrent?: number;
  defaultPageSize?: number;
  // request: (params: any) => Promise<{
  //   data: T[];
  //   total: number;
  //   [key: string]: any;
  // }>;
  immediate?: boolean;
  defaultParams?: Record<string, any>;

}

interface UseTableRequestReturn<T> {
  tableProps: {
    dataSource: T[];
    loading: boolean;
    pagination: PaginationProps;
    onChange: (pagination: PaginationProps,filters, sorter) => void;
  };
  searchParams: Record<string, any>;
  refresh: () => Promise<void>;
  setSearchParams: (params: Record<string, any>, shouldResetPagination?: boolean) => void;
  resetPagination: () => void;
  setDataSource: (data: T[]) => void;
}

export const useTableRequest = <T extends any = any>(
  options: UseTableRequestOptions<T>
): UseTableRequestReturn<T> => {
  const {
    url,
    orderBy= "id desc",
    defaultCurrent = 1,
    defaultPageSize = 10,
    // request,
    immediate = true,
    defaultParams = {},
  } = options;

  const [dataSource, setDataSource] = useState<T[]>([]);
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [pagination, setPagination] = useState({
    current: defaultCurrent,
    pageSize: defaultPageSize,
  });
  const [searchParams, _setSearchParams] = useState<Record<string, any>>(defaultParams);


  const getList = async (params) => {
    const { page, pageSize, fromDate, toDate, ...other } = params;
    const { data } = await request({
      url,
      method: "POST",
      data: {
        page,
        pageSize,
        ...other,
        ...(fromDate && toDate ? {
          fromDate: dayjs(fromDate).format('YYYY-MM-DD'),
          toDate: dayjs(toDate).format('YYYY-MM-DD')
        } : {})
      }


    });
    return {
      data: data.list,
      total: data.total
    };

  }

  // 使用 ref 存储最新的请求函数，避免重复创建
  const requestRef = useRef(getList);
  requestRef.current = getList;

  // 使用 ref 存储搜索参数，避免重复渲染
  const searchParamsRef = useRef(searchParams);
  searchParamsRef.current = searchParams;

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const { data, total: resTotal } = await requestRef.current({
        // orderBy,
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...searchParamsRef.current,
        orderBy:searchParamsRef.current.orderBy||orderBy
      });
      setDataSource(data || []);
      setTotal(resTotal || 0);
    } catch (error) {
      console.error('请求失败:', error);
      setDataSource([]);
      setTotal(0);
    } finally {
      setLoading(false);
    }
  }, [pagination.current, pagination.pageSize]);

  // 稳定的刷新函数
  const refresh = useCallback(async () => {
    await fetchData();
  }, [fetchData]);

  // 重置分页
  const resetPagination = useCallback(() => {
    setPagination({
      current: defaultCurrent,
      pageSize: defaultPageSize,
    });
  }, [defaultCurrent, defaultPageSize]);

  // 设置搜索参数
  const setSearchParams = useCallback((
    params: Record<string, any>,
    shouldResetPagination: boolean = true
  ) => {
    _setSearchParams(params);
    searchParamsRef.current = params;
    if (shouldResetPagination) {
      resetPagination();
    }
  }, [resetPagination]);

  // 处理表格变化
  const handleTableChange = useCallback((newPagination: PaginationProps,filters, sorter) => {
    console.log('handleTableChange',sorter)
    setPagination({
      current: newPagination.current || defaultCurrent,
      pageSize: newPagination.pageSize || defaultPageSize,
    });

    if(sorter.order=="ascend"){
      setSearchParams({
        ...searchParams,
        orderBy:`${sorter.field} asc`
      })

    }else if(sorter.order=="descend"){
      setSearchParams({
        ...searchParams,
        orderBy:`${sorter.field} desc`
      })
    }else{
      setSearchParams({
        ...searchParams,
        orderBy:undefined
      })
    }
  }, [defaultCurrent, defaultPageSize]);


  // 分页变化时请求
  useEffect(() => {
    fetchData();
  }, [fetchData, pagination.current, pagination.pageSize, searchParams]);

  return {
    tableProps: {
      dataSource,
      loading,
      pagination: {
        ...pagination,
        total,
        showSizeChanger: true,
        showTotal: (total) => `共 ${total} 条`,
        pageSizeOptions: ['10', '20', '50', '100'],
      },
      onChange:handleTableChange,
    },
    searchParams,
    refresh,
    setSearchParams,
    resetPagination,
    setDataSource,
  };
};